<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script type="text/javascript" src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
    <script type="text/javascript" src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.js"></script>

</head>
<body>
<div>
    <button onclick="onConnect()">连接</button>
    <button onclick="onSendPublic()">发送给所有人</button>
    <button onclick="onSendPrivate()">发送给私人</button>
    <button onclick="onDisconnect()">断开</button>
</div>
</body>
<script>
    var client = null;
    function onConnect() {
        console.debug('onConnect')
        var stomp = new SockJS("http://120.55.241.14:8080/stomp")
        // var stomp = new SockJS("http://localhost:8080/stomp")
        client = Stomp.over(stomp);
        client.connect({}, onSuccess, onError)
    }

    // headers为订阅消息队列的补充信息,用于后端校验，已经用用户名作校验了，此处可以不填
    var headers1 = {};
    var headers2 = {};
    const onSuccess = () => {
        console.log('连接成功 --------')
        //接收公共消息
        client.subscribe("/topic/topic.web.public.routingkey",function (message) {
            console.log("收到消息public："+message)
            // 消息处理...
        },headers1)
        // 接收发给自己的私人消息
        client.subscribe('/user/topic/topic.web.private.routingkey', function (message) {
            console.log("收到消息private："+message)
            // 消息处理...
        },headers2);

    }

    const onError = (error) => {
        console.error('连接失败:', error);
    }

    function onDisconnect() {
        if (client != null) {
            client.disconnect();
        }
        console.log("Disconnected");
    }
    // 发送消息给所有人
    function onSendPublic() {
        console.debug('onSendPublic')
        var jsonStr = {"test1": "value1", "test2": "value2"}
        client.send('/app/public', {}, JSON.stringify(jsonStr));
    }

    // 发送消息给私人
    function onSendPrivate() {
        console.debug('onSendPrivate')
        var jsonStr = {"test1": "value1", "test2": "value2"}
        username = "wu001";
        // userId = 192
        client.send('/app/private/'+username, {}, JSON.stringify(jsonStr));
        // username1 = "user111";
        // client.send('/app/private/'+username1, {}, JSON.stringify(jsonStr));
    }
</script>
</html>